package dao.Impl;

import bean.Grade;
import bean.Student;
import dao.Dao;
import util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DaoImpl extends DruidUtil implements Dao {
    @Override
    public Grade findByGid(int gid) {
        Grade grade = new Grade();
        List<Student> studentList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement("select * from student s,grade g where s.gid = g.gid and g.gid = ?");
            preparedStatement.setInt(1,gid);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                //1.分别获取信息
                Student student = new Student();
                student.setSname(resultSet.getString("sname"));
                grade.setGname(resultSet.getString("gname"));
                //2.建立联系
                studentList.add(student);
            }
            grade.setStudentList(studentList);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(connection,preparedStatement,resultSet);
        }
        return grade;
    }

    @Override
    public Student findBySid(int sid) {
        Student student = new Student();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement("select * from student s,grade g where s.gid = g.gid and s.sid = ?");
            preparedStatement.setInt(1,sid);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                //1.分别获取信息
                student.setSname(resultSet.getString("sname"));
                Grade grade = new Grade();
                grade.setGname(resultSet.getString("gname"));
                //2.建立联系
                student.setGrade(grade);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(connection,preparedStatement,resultSet);
        }
        return student;
    }
}
